package org.adit.spring.hibernate.service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.adit.spring.hibernate.dao.OrderServiceDao;
import org.adit.spring.hibernate.entity.Endereco;
import org.adit.spring.hibernate.entity.OrderService;
import org.adit.spring.hibernate.util.CsvReader;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.ioc.Component;

@Component
public class FileService {
	@Autowired
	private OrderServiceDao dao;

	public void readString(InputStream inputStream, OrderService os) {

		try {

			CsvReader reader = new CsvReader(inputStream);
			reader.readHeaders();
			while (reader.readRecord()) {
				String id = reader.get("id");
				String descricao = reader.get("cliente");
				String data = reader.get("data");
				String desc = reader.get("descricao");
				String rua = reader.get("rua");
				String numero = reader.get("numero");
				String bairro = reader.get("bairro");
				String cidade = reader.get("cidade");
				String cep = reader.get("cep");

				OrderService orderService = new OrderService();
				Endereco endereco = new Endereco();
				orderService.setOrderServiceName(os.getOrderServiceName());
				orderService.setId(new Long(id));
				orderService.setDescricao(descricao);
				orderService.setDataDeCriacao((Date) new SimpleDateFormat("dd/MM/yyyy").parse(data));

				orderService.setDescricao(desc);
				endereco.setRua(rua);
				endereco.setNumero(numero);
				endereco.setBairro(bairro);
				endereco.setCidade(cidade);
				endereco.setCep(cep);
				orderService.setEndereco(endereco);
				orderService.setDataDeCriacao(new Date());
				dao.salva(orderService);
			}
			reader.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

}
